package com.ruoyi.littleRedBook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.littleRedBook.domain.pojo.Order;
import com.ruoyi.littleRedBook.mapper.OrderMapper;
import com.ruoyi.littleRedBook.service.AdminOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminOrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements AdminOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public AjaxResult getAllOrders(String orderNo, Long buyerId, Integer status, Integer pageNum, Integer pageSize) {
        Page<Order> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();

        // 订单号搜索
        if (orderNo != null && !orderNo.trim().isEmpty()) {
            queryWrapper.like("order_no", orderNo.trim());
        }

        // 买家ID搜索
        if (buyerId != null) {
            queryWrapper.eq("buyer_id", buyerId);
        }

        // 状态筛选
        if (status != null) {
            queryWrapper.eq("status", status);
        }

        queryWrapper.orderByDesc("created_at"); // 按创建时间倒序
        Page<Order> orderPage = orderMapper.selectPage(page, queryWrapper);
        return AjaxResult.success(orderPage.getRecords());
    }

    @Override
    public AjaxResult getOrderDetail(Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return AjaxResult.error("订单不存在");
        }
        return AjaxResult.success(order);
    }

    @Override
    public AjaxResult getOrderStatistics() {
        Map<String, Object> statistics = new HashMap<>();

        // 1. 今日订单统计（00:00:00至今）
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        Map<String, Object> todayStats = getOrderStatsByTime(todayStart, LocalDateTime.now());
        statistics.put("todayOrderCount", todayStats.get("count"));
        statistics.put("todayOrderAmount", todayStats.get("amount"));

        // 2. 本月订单统计（月初00:00:00至今）
        LocalDateTime monthStart = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay();
        Map<String, Object> monthStats = getOrderStatsByTime(monthStart, LocalDateTime.now());
        statistics.put("monthOrderCount", monthStats.get("count"));
        statistics.put("monthOrderAmount", monthStats.get("amount"));

        // 3. 总订单统计
        Map<String, Object> totalStats = getTotalOrderStats();
        statistics.put("totalOrderCount", totalStats.get("count"));
        statistics.put("totalOrderAmount", totalStats.get("amount"));

        return AjaxResult.success(statistics);
    }

    // 按时间范围统计订单数和总金额
    private Map<String, Object> getOrderStatsByTime(LocalDateTime startTime, LocalDateTime endTime) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("created_at", startTime, endTime);

        // 订单数
        Long count = orderMapper.selectCount(queryWrapper);

        // 总金额（排除已取消/退款订单）
        queryWrapper.notIn("status", 4, 6); // 4-已取消 6-已退款
        BigDecimal amount = orderMapper.selectTotalAmount(queryWrapper);

        Map<String, Object> stats = new HashMap<>();
        stats.put("count", count);
        stats.put("amount", amount == null ? BigDecimal.ZERO : amount);
        return stats;
    }

    // 总订单统计
    private Map<String, Object> getTotalOrderStats() {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();

        // 总订单数
        Long count = orderMapper.selectCount(queryWrapper);

        // 总金额（排除已取消/退款订单）
        queryWrapper.notIn("status", 4, 6);
        BigDecimal amount = orderMapper.selectTotalAmount(queryWrapper);

        Map<String, Object> stats = new HashMap<>();
        stats.put("count", count);
        stats.put("amount", amount == null ? BigDecimal.ZERO : amount);
        return stats;
    }
}
